import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from '@/api/axios'
import router from '@/router'

interface GlobalErrorProps {
  status: boolean
  message?: string
}
interface UserProps {
  isLogin: boolean
  nickName?: string
  _id?: number
  column?: string
  email?: string
}
interface GlobalDataProps {
  error: GlobalErrorProps
  token: string
  isLoading: boolean
  user: UserProps
}

export const useMainStore = defineStore('main', () => {
  // ref  ----  state
  const error = ref<GlobalErrorProps>()
  const tokenStr = localStorage.getItem('') || ''
  const token = ref<string>(tokenStr)
  const isLoading = ref<boolean>(false)
  const user = ref<UserProps>({
    isLogin: false,
  })

  // computed  ---  getter

  // function  ---  action
  // 登进
  function login<T extends UserProps & Record<'token', 'string'>>(rawData: T) {
    const { token: newToken } = rawData
    token.value = newToken
    localStorage.setItem('token', newToken)
    axios.defaults.headers.common.Authorization = `Bearer ${newToken}`
  }
  // 登出
  function logout() {
    const { reuqiredLogin } = router.currentRoute.value.meta
    token.value = ''
    user.value = { isLogin: false }
    localStorage.removeItem('token')
    delete axios.defaults.headers.common.Authorization
    if (reuqiredLogin) {
      router.push('/')
    }
  }
  // 登录更新用户信息
  function fetchUser<T extends Omit<UserProps, 'isLogin'>>(rawData: T) {
    user.value = { isLogin: true, ...rawData }
  }
  return {
    error,
    token,
    isLoading,
    user,
    login,
    logout,
    fetchUser,
  }
})
